package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/3/3 13:55
 */

public class FileUploadDialgFragment extends DialogFragment {

  public static final String EXTRA_PATH =
      FileUploadDialgFragment.class.getSimpleName() + ".EXTRA_PATH";
  private static final String EXTRA_ID =
      FileUploadDialgFragment.class.getSimpleName() + ".EXTRA_ITEM";
  private static final String EXTRA_TABLENAME =
      FileUploadDialgFragment.class.getSimpleName() + ".EXTRA_TABLENAME";
  /** 是否需要缩略图 */
  private static final String EXTRA_IS_NEED_SUBIMAGE =
      FileUploadDialgFragment.class.getSimpleName() + ".EXTRA_IS_NEED_SUBIMAGE";
  private String mFileName;
  @SuppressWarnings("all") private AlertDialog mAlertDialog;
  //private ProgressDialog mProgressDialog;
  private String mId;
  private String mFilePath;
  private String mTableName;
  private BaseVolleyActivity mActivity;
  private View mView;
  private TextView mTvFileName;
  private TextView mTvHintUpload;
  private ProgressBar mPbUpload;
  /** 是否需要缩略图 */
  private boolean mIsNeedSubImage;
  private CallBack mCallBack;

  public static FileUploadDialgFragment newInstance(String url, String id, String tableName) {
    return newInstance(url, id, tableName, false);
  }

  /**
   * @param isNeedSubImage 给网页端自动生成缩略图
   */
  public static FileUploadDialgFragment newInstance(String url, String id, String tableName,
      boolean isNeedSubImage) {
    Bundle argsBundle = new Bundle();
    argsBundle.putString(EXTRA_PATH, url);
    argsBundle.putString(EXTRA_ID, id);
    argsBundle.putString(EXTRA_TABLENAME, tableName);
    argsBundle.putBoolean(EXTRA_IS_NEED_SUBIMAGE, isNeedSubImage);
    FileUploadDialgFragment fragment = new FileUploadDialgFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mFilePath = getArguments().getString(EXTRA_PATH);
    mId = getArguments().getString(EXTRA_ID);
    mTableName = getArguments().getString(EXTRA_TABLENAME);
    mIsNeedSubImage = getArguments().getBoolean(EXTRA_IS_NEED_SUBIMAGE, false);
    mFileName = FileUtil.getFileNameByFilePath(mFilePath);
    mActivity = (BaseVolleyActivity) getActivity();
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    mAlertDialog = initAlertDialog();
    //mProgressDialog = initProgressDialog();
    return mAlertDialog;
  }

  private AlertDialog initAlertDialog() {
    mAlertDialog = new AlertDialog.Builder(getActivity()).setPositiveButton("上传", null)
        .setNegativeButton(android.R.string.cancel, null)
        .create();
    mAlertDialog.setTitle("文件上传");
    mView = initView();
    mAlertDialog.setView(mView);
    mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
      @Override public void onShow(DialogInterface dialog) {
        Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        b.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View v) {
            new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE,
                mTableName, mId, new myUpLoadHandler(), mIsNeedSubImage);
            updateDialog();
          }
        });
      }
    });
    return mAlertDialog;
  }

  private View initView() {
    mView = LayoutInflater.from(mActivity).inflate(R.layout.fragment_upload, null, false);
    mTvFileName = (TextView) mView.findViewById(R.id.tv_fileName);
    mTvHintUpload = (TextView) mView.findViewById(R.id.tv_hintUpload);
    mPbUpload = (ProgressBar) mView.findViewById(R.id.pb_upload);
    mTvFileName.setText(mFileName);
    String message = "您选择了文件 <br><br> <font color='blue'> " + mFileName + "</font><br><br>是否确定上传";
    mTvHintUpload.setText(Html.fromHtml(message));
    mPbUpload.setMax(100);
    mPbUpload.setProgress(0);
    mTvFileName.setVisibility(View.GONE);
    mPbUpload.setVisibility(View.GONE);
    return mView;
  }

  /**
   * 显示成progress的类型
   */
  private void updateDialog() {

    mAlertDialog.setTitle(getString(R.string.uploading));
    mTvHintUpload.setVisibility(View.GONE);
    mTvFileName.setVisibility(View.VISIBLE);
    mPbUpload.setVisibility(View.VISIBLE);
    mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setVisibility(View.GONE);
    //mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "", null)

  }

  //private ProgressDialog initProgressDialog() {
  //    ProgressDialog progressDialog = new ProgressDialog(mActivity);
  //
  //    progressDialog.setProgress(0);
  //    progressDialog.setMax(100);
  //    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  //    progressDialog.setTitle("");
  //    return progressDialog;
  //}

  public FileUploadDialgFragment setCallBack(CallBack callBack) {
    mCallBack = callBack;
    return this;
  }

  public interface CallBack {
    /** 已经提示文件上传成功,如果还需要做其他事,回调 */
    void uploadSuccess(String path);
  }

  @SuppressWarnings("deprecation") private class myUpLoadHandler extends AsyncHttpResponseHandler {

    private long mProgressTime;

    public myUpLoadHandler() {
    }

    @Override public void onProgress(long bytesWritten, long totalSize) {
      if ((System.currentTimeMillis() - mProgressTime) > 100) {
        int progress = (int) ((bytesWritten / totalSize) * 100);
        mPbUpload.setProgress(progress);
        mProgressTime = System.currentTimeMillis();
      }
    }

    @Override public void onStart() {
      //MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      ToastUtil.show(R.string.fileUploadFailure);
      //mProgressDialog.dismiss()
      mAlertDialog.dismiss();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
      if (result == null) {
        MyUtils.dismissDialog();
        ToastUtil.show(R.string.wrong_data);
        return;
      }
      if (result.getResult() != null && result.getResult().equals("1") && !TextUtils.isEmpty(
          result.getMessage())) {
        // 上传成功,再上传数据
        ToastUtil.show(R.string.fileUploadSuccess);
        String selcurFile = result.getMessage();
        if (mCallBack != null) mCallBack.uploadSuccess(selcurFile);
        Intent intent = new Intent();
        intent.putExtra(EXTRA_PATH, selcurFile);
        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);

        //mDocPath = selcurFile;
        //tvFile.setText(FileUtil.getFileNameByFilePath(selcurFile));

      } else {
        MyUtils.dismissDialog();
        ToastUtil.show(result.getMessage());
      }

      mAlertDialog.dismiss();
    }
  }
}
